package com.iocup.keybastion.sso.core;


import com.iocup.keybastion.core.lock.LocalLock;
import com.iocup.keybastion.core.lock.Lock;
import com.iocup.keybastion.core.lock.LockType;
import com.iocup.keybastion.core.store.CacheStore;
import com.iocup.keybastion.sso.ClientStoreService;
import com.pine.sunflower.core.validate.Validator;

import java.util.HashSet;
import java.util.Set;

/**
 * @author xyjxust
 * @create 2023/1/18 9:35
 **/
public class ClientStoreServiceImpl implements ClientStoreService {

    private CacheStore cacheStore;
    private Lock lock;

    private static final String LOGIN_NAME_CLIENT_ID_KEY = "LOGIN_NAME:CLIENT_ID:";


    public ClientStoreServiceImpl(Lock lock, CacheStore cacheStore) {
        Validator.build().validate(cacheStore == null, "tokenStore不能为空")
                .throwIfFail();
        this.lock = lock;
        if (lock == null) {
            this.lock = new LocalLock();
        }
        this.cacheStore = cacheStore;
    }

    @Override
    public Set<String> getByClientId(String loginName) {
        return cacheStore.getValue(LOGIN_NAME_CLIENT_ID_KEY+loginName);
    }

    @Override
    public void saveClientId(String clientId, String loginName) {
        lock.tryLock(LockType.LOGIN_NAME,loginName, key->{
            Set<String> list =  getByClientId(loginName);
            if(list==null){
                list = new HashSet<>();
            }
            list.add(clientId);
            cacheStore.setValue(LOGIN_NAME_CLIENT_ID_KEY+loginName,list);
        });

    }

    @Override
    public void removeClientId(String loginName) {
        cacheStore.removeValue(loginName);
    }
}
